package de.medizin.uni.halle.irm;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.channels.FileChannel;
import java.util.StringTokenizer;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Toast;
//import com.Ostermiller.util.CSVParser;
import com.actionbarsherlock.app.SherlockFragment;

import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
 
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;



public class ImpExpFragment extends SherlockFragment {
	
	SQLiteDatabase database;
	Cursor c;
	final Context context = getSherlockActivity();
	
	
	public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
	
		final View rm = (RelativeLayout)inflater.inflate(R.layout.impexp, container, false);
		((Button) rm.findViewById(R.id.restorebutton)).setOnClickListener(new OnClickListener(){
			@Override
		public void onClick(View arg0) {
				restoreDB();
			}			
		});
		((Button) rm.findViewById(R.id.backupbutton)).setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View arg0) {
				backupDB();
			}			
		});
		((Button) rm.findViewById(R.id.exportbutton)).setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View arg0) {
				exportData();
			}			
		});
		((Button) rm.findViewById(R.id.importbutton)).setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View arg0) {
				try{
					String line;
					FileReader fr = new FileReader(Environment.getExternalStorageDirectory()+"/datei.csv");
				    BufferedReader br = new BufferedReader(fr);
					while((line = br.readLine()) != null) {
					    StringTokenizer st = new StringTokenizer(line, ",");
					    String name = st.nextToken();
					    String email = st.nextToken();
					    Integer id = Integer.valueOf(st.nextToken());
					}					
				} catch (Exception e) {
					e.printStackTrace();
				}
			}			
		});
        return rm;        
	}
	
    private void backupDB() {
        try {
            File sd = Environment.getExternalStorageDirectory();
            File data = Environment.getDataDirectory();

            if (sd.canWrite()) {
                String currentDBPath = "//data//de.medizin.uni.halle.irm//databases//born";
                String backupDBPath = "bornbackup";
                File currentDB = new File(data, currentDBPath);
                File backupDB = new File(sd, backupDBPath);
                DESEncryption.encrypt(sd,new FileInputStream(currentDB));
                database = getSherlockActivity().openOrCreateDatabase("born", Context.MODE_PRIVATE, null);
                database.delete("patients", null , null);
                Toast.makeText(getSherlockActivity().getBaseContext(), "Erfolgreich gespeichert: "+ backupDB.toString(), Toast.LENGTH_LONG).show();

            }
            Toast.makeText(getSherlockActivity().getBaseContext(),"Ging nicht", Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            Toast.makeText(getSherlockActivity().getBaseContext(), e.toString(), Toast.LENGTH_LONG).show();
        }
    }   
	
	private void restoreDB() {			
        try {
	        File sd = Environment.getExternalStorageDirectory();
	        File data = Environment.getDataDirectory();

            if (sd.canWrite()) {
                String currentDBPath = "//data//de.medizin.uni.halle.irm//databases//born";
                String backupDBPath = "bornbackup";
                File currentDB = new File(data, currentDBPath);
                File backupDB = new File(sd, backupDBPath);                
                DESEncryption.decrypt(sd);
                String restoreDBPath = "bornrestore";
                File restoreDb = new File(sd, restoreDBPath);
                
                currentDB.createNewFile();
                copyFile(restoreDb, currentDB); 
            }	
        return;            
		} 
        catch (Exception e) {
	        e.printStackTrace();
			Toast.makeText(getSherlockActivity().getBaseContext(), "Daten konnten nicht geschrieben werden.", Toast.LENGTH_SHORT).show();
	        return;
	    }	       
	}	
	
	private void exportData() {		
		try{
			File file = new File(Environment.getExternalStorageDirectory(),"Export.txt");
			FileWriter writer;
			writer = new FileWriter(file ,true);
			database = getSherlockActivity().openOrCreateDatabase("born", Context.MODE_PRIVATE, null);
			Cursor h = database.rawQuery("SELECT * FROM patients p , history h WHERE p.sid = h.sid; ", null);
			h.moveToFirst();
			while(h.moveToNext()){
	//			System.out.println(h.getColumnName(0));
	//			System.out.println(h.getString(h.getColumnIndex("sid")) +" "
	//					+h.getString(h.getColumnIndex("historytype"))+" "
	//					+h.getString(h.getColumnIndex("type"))
	//					+" "+h.getString(h.getColumnIndex("content"))+" "
	//					+h.getString(h.getColumnIndex("evaluation"))+" "
	//					+h.getString(h.getColumnIndex("comment")));
				writer.write(h.getString(h.getColumnIndex("sid")) +" "
				+h.getString(h.getColumnIndex("historytype"))+" "
				+h.getString(h.getColumnIndex("type"))
				+" "+h.getString(h.getColumnIndex("content"))+" "
				+h.getString(h.getColumnIndex("evaluation"))+" "
				+h.getString(h.getColumnIndex("comment")));
				writer.write(System.getProperty("line.separator"));	
				writer.flush(); 
			} 
		writer.close();
		}catch (Exception E) {
				E.printStackTrace();
		}	
	}

	private static void copyFile(File src, File dst) throws IOException {
		FileChannel inChannel = new FileInputStream(src).getChannel();
		FileChannel outChannel = new FileOutputStream(dst).getChannel();
		try {
			inChannel.transferTo(0, inChannel.size(), outChannel);
		} finally {
			if (inChannel != null)
				inChannel.close();
			if (outChannel != null)
				outChannel.close();
		}
	}
}